package com.thuan.android3d;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.os.SystemClock;
import android.util.Log;

public class GLRenderer implements Renderer {
    
	private final String TAG = "GLRenderer";
	private final long CONST_FPS = 30;
	private long curTime;
	private long prevTime;
    private Triangle triangle;
    private Triangle1 triangle1;
    private float xAngle;
    private Context context;
    private Sprite[] sprites;
    
    public GLRenderer(Context context) {
    	this.context = context;
    	sprites = new Sprite[2];
		sprites[0] = new Sprite(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher), 200, 100);
		sprites[1] = new Sprite(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_search), 100, 100);
    }
   
    public float getxAngle() {
		return xAngle;
	}
	public void setxAngle(float xAngle) {
		this.xAngle = xAngle;
	}
	public float getyAngle() {
		return yAngle;
	}
	public void setyAngle(float yAngle) {
		this.yAngle = yAngle;
	}

	private float yAngle;
    
	
	public void onDrawFrame(GL10 gl) {
		
		prevTime = System.currentTimeMillis();
		
		gl.glClearColor(0f, 0f, 0f, 1.0f);
        
		//reset matrix
        gl.glLoadIdentity();
        
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            
        // set rotation
        gl.glRotatef(xAngle, 1f, 0f, 0f);
        gl.glRotatef(yAngle, 0f, 1f, 0f);
  
        sprites[0].draw(gl);
        sprites[1].draw(gl);
    
        curTime = System.currentTimeMillis();
        
        
        long time = curTime - prevTime;
        long wantedTime = 1000/CONST_FPS;
        
        Log.d(TAG, "" + wantedTime);
        
        if (time < wantedTime) {
        	try {
				Thread.sleep((wantedTime - time));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}
	
	public Sprite[] getSprites() {
		return sprites;
	}
	
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// TODO Auto-generated method stub
		if (height == 0) { // Prevent A Divide By Zero By
			height = 1; // Making Height Equal One
		}
		gl.glViewport(0, 0, width, height); // Reset The Current Viewport
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glOrthof(0, width, 0, height, -1, 1);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// TODO Auto-generated method stub
		gl.glEnable(GL10.GL_CULL_FACE);
		gl.glFrontFace(GL10.GL_CCW);
		gl.glCullFace(GL10.GL_BACK);
	}
}
